<?php

namespace App\Console\Commands;

use App\Utils\ArrayUtils;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class MakeCRUDCommand extends MakeRoutesCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'create:crud';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Generate resource CRUD for config/api.*.php";




    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $resource = $this->argument('resource');
        $parent = explode('-', $resource);
        if (count($parent) > 2) {
            echo "resource level depth should not be greater than 2";
            return;
        }
        $resource = array_pop($parent);
        $meta = parent::getMetaData($resource);
        $primary_key = $meta["primary_key"];
        $controller = Str::title(Str::singular($resource));
        $route = "/$resource";
        $idRoute = "/$resource/{" . $primary_key . "}";

        if (count($parent) > 0) {
            $parent = $parent[0];
            $parentName = Str::title(Str::singular($parent));
            $parentPath = "/$parent/{" . $primary_key . "}";
            $controller = $parentName . $controller;
            $route = $parentPath . $route;
            $idRoute = $parentPath . $idRoute;

        }

        $data = [
            'resource' => $this->argument('resource'),
            'controller' => $this->to_camel($controller),
            'route' => $route,
            'idRoute' => $idRoute,
            'meta' => $meta,
            'primary_key' => $primary_key
        ];

        $this->putCommonVariables($data);
        $this->doGenerate($data);

        // 生成 CRUD 后立即更�? routes.auto_generate.php 文件
        // $this->makeRoutes();
    }


    protected function doGenerate($data)
    {
        $this->files = new Filesystem();

        $basePath = app()->basePath();
        $filePath = $basePath . "/config/validate/api." . $data['resource'] . ".php";
        if ($this->files->exists($filePath)) {
            echo "config/validate/api." . $data['resource'] . ".php already exists\n";
            return;
        }

        $content = view('stubs/crud', $data);
        $this->files->put($filePath, $content);
        echo $filePath . " generated\n";
    }

    protected function getArguments()
    {
        return [
            ['resource', InputArgument::REQUIRED, 'specify the resource name. Seperate by "-". ex: users-kns']
        ];
    }
}